package es.us.lsi.aws.api.server.dao;

import java.util.StringTokenizer;

import org.apache.commons.codec.binary.Base64;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;

public class DAOAuthentication {
	
	@SuppressWarnings("deprecation")
	public static boolean isValidUser(String authorizationHeader) {

		//TODO cambiar
		boolean valid = true;
		String username = null;
		String password = null;

		if (authorizationHeader != null) {
			StringTokenizer st = new StringTokenizer(authorizationHeader);
			if (st.hasMoreTokens()) {
				String basic = st.nextToken();

				if (basic.equalsIgnoreCase("Basic")) {
					String credentials = st.nextToken();

					String userPass = new String(
							Base64.decodeBase64(credentials));

					int p = userPass.indexOf(":");
					if (p != -1) {
						username = userPass.substring(0, p);
						password = userPass.substring(p + 1);

					}

					// Modificar esto
//					valid = username.equals("ola") && password.equals("kase");
					DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
					Query q = new Query("User");
					Filter f1 = new FilterPredicate("username", FilterOperator.EQUAL, username);
					Filter f2 = new FilterPredicate("password", FilterOperator.EQUAL, password);
					Filter f3 = CompositeFilterOperator.and(f1,f2);
					q.setFilter(f3);
					
					valid = datastore.prepare(q).asSingleEntity()!=null;
				}
			}
		}

		return valid;
	}

}
